package com.fg114.main.util;

import java.io.FileInputStream;
import java.io.InputStream;

import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class PictureUtils {
	private static final int IMAGE_SIZE = 500; // 图片边长限制
	private static final int IMAGE_QUALITY = 66; // 图片压缩率
	private static final int MAX_SIDE_OF_BITMAP = 500; // 图片的最大边长限制

	// 获取位图
	public static Bitmap getBitmap(Context context, String path) {

		ContentResolver contentResolver = context.getContentResolver();
		InputStream picStream = null; // 图片流
		if (path == null || path.equals("")) {
			DialogUtil.showToast(context, "图片路径为空!");
			return null;
		}
		try {
			picStream = new FileInputStream(path);
			// picStream =
			// contentResolver.openInputStream(Uri.parse(mImageUri));
			if (picStream.available() == 0) {
				DialogUtil.showToast(context, "图片数据无效");
				return null;
			}
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			// 获取图片的宽和高
			BitmapFactory.decodeStream(picStream, null, options); // 此时返回bm为空
			options.inJustDecodeBounds = false;

			if (options.outWidth < 0 || options.outHeight < 0) {
				// 选中的是非图像文件
				DialogUtil.showToast(context, "图片格式无效");
				return null;
			}

			// 计算缩放比
			int scale = 1;
			if (options.outWidth > IMAGE_SIZE || options.outHeight > IMAGE_SIZE) {
				if (options.outWidth >= options.outHeight) {
					scale = (int) Math.ceil(options.outWidth
							/ (float) IMAGE_SIZE);
				} else {
					scale = (int) Math.ceil(options.outHeight
							/ (float) IMAGE_SIZE);
				}
			}
			options.inSampleSize = scale;
			picStream.close();
			// picStream =
			// contentResolver.openInputStream(Uri.parse(mImageUri));
			picStream = new FileInputStream(path);
			Bitmap bmp = BitmapFactory.decodeStream(picStream, null, options);
			return bmp;
		} catch (Exception e) {
//			DialogUtil.showToast(context, "载入图片出错");
			Log.e("载入图片出错", "" + e.getMessage(), e);
			return null;
		} finally {
			if (picStream != null) {
				try {
					picStream.close();
				} catch (Exception e) {
					DialogUtil.showToast(context, e.getMessage());
				}

			}
		}
	}

	public static  Bitmap scaleBitmap(Bitmap old) {

		// 没有超过边长，直接返回
		int height = old.getHeight();
		int width = old.getWidth();
		if (width <= MAX_SIDE_OF_BITMAP && height <= MAX_SIDE_OF_BITMAP) {
			return old;
		}
		// 按比例缩小到MAX_SIDE_OF_BITMAP

		// 缩放比例
		float scale = 1;
		if (height > width) {

			scale = MAX_SIDE_OF_BITMAP / ((float) height);
		} else {
			scale = MAX_SIDE_OF_BITMAP / ((float) width);
		}
		try {
			return Bitmap.createScaledBitmap(old, (int) (width * scale),
					(int) (height * scale), false);

		} finally {
			if (old != null) {
				old.recycle();
				old = null;
			}
		}
	}
}
